<?php
namespace App\Http\Logic;

use App\Models\SwtArticle;
use App\Models\SwtInfoDisclosure;
use App\Models\SwtPolicy;
use App\Models\SwtPortalConfig;
use Illuminate\Support\Facades\Storage;
use Str;

class PortalLogic extends CommonLogic
{
    public static function getArticleList($params, $page_no = 1, $page_size = 10)
    {
        $offset = ($page_no - 1) * $page_size;

        $search = [
            ['status','=',1]
        ];

        if(key_exists('type', $params) && $params['type']) {
            $search[] = ['type','=',$params['type']];
        }

        if(key_exists('show_index', $params) && $params['show_index']) {
            $search[] = ['show_index','=',$params['show_index']];
        }

        if(key_exists('show_mini', $params) && $params['show_mini']) {
            $search[] = ['show_mini','=',$params['show_mini']];
        }

        $arr = SwtArticle::where($search)
            -> orderBy('sort', 'desc')
            -> orderBy('id', 'desc')
            -> limit($page_size)
            -> offset($offset)
            -> get();

        $count = SwtArticle::where($search)->count();

        if($arr) {
            $arr = $arr -> toArray();
        }

        foreach ($arr as &$item)
        {
            $item['image'] = $item['image'] ? asset(Storage::url($item['image'])) : "";
        }

        $data = [
            'list'          => $arr,
            'page_no'       => $page_no,
            'page_size'     => $page_size,
            'count'         => $count,
            'more'          => count($arr) >= $page_size
        ];

       return $data;
    }

    public static function getHonorList() {
        $search = [
            ['status','=',1],
            ['type','=', 'honor'],
        ];

        $arr = SwtArticle::where($search)
            -> orderBy('sort', 'desc')
            -> get();

        if($arr) {
            $arr = $arr -> toArray();
        }

        usort($arr, function($a, $b) {
            return strtotime($b['show_time']) - strtotime($a['show_time']);
        });

        $result = [];

        foreach ($arr as $item) {
            $item['image'] = $item['image'] ? asset(Storage::url($item['image'])) : "";

            $timestamp = strtotime($item['show_time']);
            $year = (int)date('Y', $timestamp);
            $month = (int)date('n', $timestamp);

            // 查找年份是否已经存在
            $yearIndex = null;
            foreach ($result as $key => $yearGroup) {
                if ($yearGroup['year'] === $year) {
                    $yearIndex = $key;
                    break;
                }
            }

            if ($yearIndex === null) {
                // 年份不存在，创建新年份组
                $result[] = [
                    'year' => $year,
                    'data' => []
                ];
                $yearIndex = count($result) - 1;
            }

            // 查找月份是否存在
            $monthIndex = null;
            foreach ($result[$yearIndex]['data'] as $key => $monthGroup) {
                if ($monthGroup['month'] === $month) {
                    $monthIndex = $key;
                    break;
                }
            }

            if ($monthIndex === null) {
                // 月份不存在，创建新月份组
                $result[$yearIndex]['data'][] = [
                    'month' => $month,
                    'list' => []
                ];
                $monthIndex = count($result[$yearIndex]['data']) - 1;
            }

            // 把当前文章放到对应的年份-月份组里
            $result[$yearIndex]['data'][$monthIndex]['list'][] = $item;
        }

        // 按年份倒序排序（如果需要）
        usort($result, function($a, $b) {
            return $b['year'] - $a['year'];
        });

        // 按月份倒序排序（如果需要）
        foreach ($result as &$yearGroup) {
            usort($yearGroup['data'], function($a, $b) {
                return $b['month'] - $a['month'];
            });
        }

        return $result;
    }

    public static function getArticleInfo($id)
    {
        $arr = SwtArticle::find($id);

        if(!$arr) {
            return [];
        }

        $arr -> image = $arr -> image ? asset(Storage::url($arr -> image)) : "";

        return $arr->toArray();
    }
    public static function getArticleFirst($params)
    {

        $search = [
            ['status','=',1]
        ];

        if(key_exists('type', $params) && $params['type']) {
            $search[] = ['type','=',$params['type']];
        }

        if(key_exists('show_index', $params) && $params['show_index']) {
            $search[] = ['show_index','=',$params['show_index']];
        }

        $arr = SwtArticle::where($search) -> orderBy('sort', 'desc')-> orderBy('id', 'desc')  -> first();

        if(!$arr) {
            return [];
        }

        $arr -> image = $arr -> image ? asset(Storage::url($arr -> image)) : "";

        return $arr->toArray();
    }

    public static function getConfig($key)
    {
        $info = SwtPortalConfig::where('key', $key)->first();

        if(!$info) {
            self::$error = "未找到此配置";
            return false;
        }

        $data = $info['value'];

        if($data == "") {
            $data = $info['content'];
        }

        if (Str::contains($key, 'photos') || Str::contains($key, 'pay_code')) {
            $files = explode(",", $data);

            $data = array_map(function($v) {
                return asset(\Storage::url($v));
            },$files);
        }

        if(in_array($key, ['user_org','user'])) {
            return asset(\Storage::url($data));
        }

        return $data;
    }

    public static function getDisclosureList($params, $page_no = 1, $page_size = 10)
    {
        $offset = ($page_no - 1) * $page_size;

        $search = [
            ['status','=',1]
        ];

        if(key_exists('sub_type', $params) && $params['sub_type']) {
            $search[] = ['type','=',$params['sub_type']];
        }

        $arr = SwtInfoDisclosure::where($search)
            -> orderBy('sort', 'desc')
            -> limit($page_size)
            -> offset($offset)
            -> get();

        $count = SwtInfoDisclosure::where($search)->count();

        if($arr) {
            $arr = $arr -> toArray();
        }

        foreach ($arr as &$item)
        {
            $item['path'] = $item['path'] ? asset(Storage::url($item['path'])) : "";
        }

        $data = [
            'list'          => $arr,
            'page_no'       => $page_no,
            'page_size'     => $page_size,
            'count'         => $count,
            'more'          => count($arr) >= $page_size
        ];

        return $data;
    }

    public static function getPolicyList($page_no = 1, $page_size = 10)
    {
        $offset = ($page_no - 1) * $page_size;

        $search = [
            ['status','=',1]
        ];

        $arr = SwtPolicy::where($search)
            -> orderBy('sort', 'desc')
            -> limit($page_size)
            -> offset($offset)
            -> get();

        $count = SwtPolicy::where($search)->count();

        if($arr) {
            $arr = $arr -> toArray();
        }

        $data = [
            'list'          => $arr,
            'page_no'       => $page_no,
            'page_size'     => $page_size,
            'count'         => $count,
            'more'          => count($arr) >= $page_size
        ];

        return $data;
    }
}
